package com.alibaba.dongbao.utils.interceptor;

import com.alibaba.dongbao.utils.annotations.LoginToken;
import com.alibaba.dongbao.utils.jwt.JwtUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ：Mr.ZJW
 * @date ：Created 2022/2/28 10:24
 * @description：Token校验器
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * @Author: Mr.ZJW
     * @Description:
     * @param [request, response, object=等于token注解加上的那个方法自身]
     * @Date: 2022/4/27 13:59
    **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws LoginException {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        //获取加上Token验证的方法
        HandlerMethod handlerMethod = (HandlerMethod)object;
        Method method = handlerMethod.getMethod();
        //判断请求的方法有没有加入Token验证
        if (method.isAnnotationPresent(LoginToken.class)){
            //获取请求头的Token
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)){
                throw new TokenExpiredException("token为空，请重新登录");
            }
            //获取方法上登录Token,解析Token是否正确
            LoginToken annotation = method.getAnnotation(LoginToken.class);
            if (annotation.required()){
                try {
                    JwtUtil.parseToken(token);
                    return true;
                }catch (Exception e){
                    throw new TokenExpiredException("Token失效或者不正确，请重新登录");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}



